package com.tenbent.product.base.core;

import com.tenbent.product.base.config.RootConfig;
import com.tenbent.product.base.config.WebConfig;
import com.tenbent.product.base.filter.TenbentFilter;
import com.tenbent.product.base.listener.TenbentListener;
import com.tenbent.product.base.listener.TenbentSessionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.*;

/**
 * 根据servlet3.0规范容器在启动的时候会自动加载初始化器WebInitializer
 *
 * 在此初始化器中配置web应用的contenxtLoad，servlet，filter等配置信息
 *
 * @author Randy
 *
 *         Created by ThinkPad on 2017/7/24.
 */
public class TenbentWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	private static final Logger logger = LoggerFactory.getLogger(TenbentWebApplicationInitializer.class);

	private static final String SERVLET_NAME = "ten_bent";

	/**
	 * 应用上下文，除web部分
	 *
	 * ContextLoaderListener 应用上下文中的 beans
	 */
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[] { RootConfig.class };
	}

	/**
	 * 应用上下文，web部分
	 *
	 * 定义 DispatcherServlet 应用上下文中的 beans
	 */
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[] { WebConfig.class };
	}

	/**
	 * DispatcherServlet的映射路径
	 */
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}

	/**
	 * 注册过滤器，映射路径与DispatcherServlet一致，
	 * 路径不一致的过滤器需要注册到另外的WebApplicationInitializer中
	 */
	@Override
	protected Filter[] getServletFilters() {
		CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
		characterEncodingFilter.setEncoding("UTF-8");
		characterEncodingFilter.setForceEncoding(true);
		TenbentFilter tenbentFilter = new TenbentFilter();
		tenbentFilter.setNonLoginUrls(new String[] { "/aip", "/login", "/login.jsp" });
		return new Filter[] { characterEncodingFilter, tenbentFilter };
	}

	@Override
	protected void customizeRegistration(ServletRegistration.Dynamic registration) {
		// 配置上传(临时文件目录，上传文件最大容量，整个multipart的容量，0代表上传文件默认写入磁盘)
		registration
				.setMultipartConfig(new MultipartConfigElement("/temp/product/center/uploads", 2097152, 4194304, 0));
	}

	/**
	 * 容器启动的时候配置(监听等)
	 *
	 */
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		// 配置监听器
		servletContext.addListener(RequestContextListener.class);
		servletContext.addListener(TenbentListener.class);
		servletContext.addListener(TenbentSessionListener.class);
		super.onStartup(servletContext);
	}

	@Override
	protected String getServletName() {
		logger.info(" servlet name is : {}", SERVLET_NAME);
		return SERVLET_NAME;
	}
}
